/**
 *
 */
package runtime;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import javax.sql.DataSource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.jdbc.datasource.init.DatabasePopulatorUtils;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * @author downpour
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath*:/payment/applicationContext-*.xml", "classpath*:/payment/dev/applicationContext-*.xml" })
@ActiveProfiles(value = { "dev" })
public class PaymentDatabaseSetting {

    private static final Logger logger = LoggerFactory.getLogger(PaymentDatabaseSetting.class);

    @Autowired
    private DataSource dataSource;

    /**
     * Initialize schema
     *
     * @throws Exception
     */
    @Test
    public void initSchema() throws Exception {

        logger.info("Setting up schema...");

        Resource script = new ClassPathResource("schema/schema.sql");

        ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
        populator.addScript(script);
        populator.setSqlScriptEncoding("UTF-8");

        String url = "jdbc:mysql://127.0.0.1:3306/";

        // Read username from input stream
        logger.info("Your database connection user name: ");
        String name = new BufferedReader(new InputStreamReader(System.in)).readLine();

        // Read password from input stream
        logger.info("Your database connection password: ");
        String password = new BufferedReader(new InputStreamReader(System.in)).readLine();

        DatabasePopulatorUtils.execute(populator, new DriverManagerDataSource(url, name, password));

    }

    /**
     * Initialize data
     */
    @Test
    public void initData() {

        logger.info("Setting up init data.");

        Resource script = new ClassPathResource("schema/init_data.sql");
        ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
        populator.addScript(script);
        populator.setSqlScriptEncoding("UTF-8");

        DatabasePopulatorUtils.execute(populator, dataSource);
    }

}
